import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/userStore";
import { storeToRefs } from "pinia";
import axios from "axios";
import type { Form } from "@/interface/formData";
import formData from "@/tool/data/formData";
import { cloneDeep } from "lodash";
import { useRouter } from "vue-router";
import { useJobTakerStore } from "@/stores/useJobTakerStore";

export default function () {

    const jobTakerStore = useJobTakerStore();
    const router = useRouter();
    const userStore = useUserStore();
    const { useridentityfer, username_store } = storeToRefs(userStore);

    const Form = formData();

    //表格数据
    // const tableData = ref<Form[]>(Form.value);
    let tableData = ref<Form[]>([]);
    let formatTable = ref<Form[]>([]);


    let isEdit = ref({
        publisher: false,
        status: false,
        title: false,
        maxPeople: false,
        description: false,
        price: false,
        taker: false,
        createdTime: false,
        startTime: false,
        publishTime: false,
        jobType: false,
        autoPublish: false,
    }); //控制表单内容是否可编辑

    const drawer = ref(false); //侧边栏显示标志

    const currentRowData = ref<Form>({
        //存储一条数据的变量
        id: 0,
        userIdentifier:0,
        userName: "",
        jobType: "",
        status: "",
        title: "",
        maxPeople: 0,
        description: "",
        salary: 0,
        process: "",
        takersId: [],
        takersName: [],
        createdTime: new Date(),
        startTime: new Date(),
        endTime: new Date(),
        publishTime: new Date(),
        autoPublish: true,
    });

    let optionItem = ref({
        selectedValue: "",
        option: [
            { value: "1", label: "零工" },
            { value: "2", label: "短期兼职" },
            { value: "3", label: "长期兼职" }
        ]
    });

    function clearForm() {
        currentRowData.value = {
            id: 0,
            userIdentifier:0,
            userName: "",
            jobType: "",
            status: "",
            title: "",
            maxPeople: 0,
            description: "",
            salary: 0,
            process: "",
            takersId: [],
            takersName: [],
            createdTime: new Date(),
            startTime: new Date(),
            endTime: new Date(),
            publishTime: new Date(),
            autoPublish: true,
        };
    }

    //=========行点击函数，打开侧边栏=======================================================
    const RowClick = (row: Form) => {
        currentRowData.value = cloneDeep(row); //复制数据
        console.log("当前行信息:", currentRowData.value);
        formUnEdit(); //表单不可编辑
        switch (currentRowData.value.process) {
            case "待接取":
                stepSet(0);
                break;
            case "已接取":
                stepSet(1);
                break;
            case "经行中":
                stepSet(2);
                break;
            case "已完成":
                stepSet(3);
                break;
            case "已结算":
                stepSet(4);
                break;
            default :
                stepSet(null);
                break;
        }
        drawer.value = true; //显示侧边栏
    };
    //表单不可编辑
    function formUnEdit() {
        isEdit.value.createdTime = false;
        isEdit.value.startTime = false;
        isEdit.value.price = false;
        isEdit.value.publisher = false;
        isEdit.value.description = false;
        isEdit.value.status = false;
        isEdit.value.taker = false;
        isEdit.value.title = false;
        isEdit.value.maxPeople = false;
        isEdit.value.autoPublish = false;
        isEdit.value.jobType = false;
    }
    // ====steps的修改==========================
    const drawerKey = ref(0); //用于刷新侧边栏
    const step = ref<any>(0);
    const stepSet = (num: any) => {
        ElMessage.info("订单进度：" + num);
        if (num === null) {
            step.value = null;
        } else {
            step.value = num;
        }
        if (num == 4 || num == 5) {
            drawerKey.value++;
        }
    };
    const steps = ref({
        drawerKey: drawerKey,
        step: step,
        stepSet: stepSet,
    });


    //发布职位，打开侧边栏
    const openDrawer = () => {
        console.log("当前用户：", username_store.value);
        Object.assign(currentRowData.value, {
            id: 0,
            userName: username_store.value,
            status: "待审核",
            title: "",
            description: "",
            salary: "",
            process: null,
            taker: [""],
            startTime: new Date(),
            endTime: new Date(),
            publishTime: new Date(),
            createdTime: new Date(),
            autoPublish: 1,
        });
        // 侧边栏内容可编辑
        isEdit.value.title = true;
        isEdit.value.maxPeople = true;
        isEdit.value.description = true;
        isEdit.value.price = true;
        isEdit.value.jobType = true;
        isEdit.value.startTime = true;
        isEdit.value.autoPublish = true;
        stepSet(null);
        //打开侧边栏
        drawer.value = true;
    };
    // 侧边栏提交方法、


    const handleSubmit = async () => {
        try {
            const newRow = {
                ...currentRowData.value, // 保留当前输入的值
                userIdentifier: useridentityfer.value as number,//用户编号
                status: "1",//职位状态
                jobType: optionItem.value.selectedValue,//职位类型
            };

            // 发送请求
            const response = await addWork(newRow);
            // 确保 response.data 存在并且 code === 200
            if (response?.data?.code === 200) {

                ElMessage.success("添加成功：" + currentRowData.value.title);
                tableData.value.push(newRow); // 使用后端返回的数据
                formatTableData(tableData.value);
                drawer.value = false; // 关闭抽屉
                clearForm();
            } else {
                ElMessage.error("添加失败：" + response?.data?.message || "未知错误");
            }
        } catch (error) {
            console.error("添加失败", error);
        }
    };

    // 侧边栏更新方法
    const handleUpdate = () => {
        alert("Updating data:" + currentRowData.value);
        // 在这里执行更新操作
        // 比如调用接口或更新数据

        drawer.value = false; // 更新后关闭抽屉
    };

    //表格编辑按钮
    const handleDetail = (row: Form) => {
        ElMessage.info("详情  " + row.id + "->" + row.title);
        currentRowData.value = cloneDeep(row);
        drawer.value = true;
    };
    //表格删除按钮
    const handleDelete = (row: Form) => {
        ElMessage.info("删除  " + row.id + "->" + row.title);
    };

    //  表格复选框===================================================================================
    const multipleSelection = ref<Form[]>([]);

    const handleSelectChange = (val: Form[]) => {
        multipleSelection.value = val;
        console.log("选中的兼职：", multipleSelection.value);
    };
    const selectable = (row: Form) => !([] as number[]).includes(row.id);

    // =界面条件筛选============================================================================

    let publisher = ref("");
    let status = ref("");
    let title = ref("");

    const flitItem = ref({ publisher, status, title });
    const FlitTableData = computed(() => {
        if (!status.value && !publisher.value && !title.value)
            return formatTable.value;
        return formatTable.value.filter((item: Form) => {
            const matchStatus = status.value
                ? item.status.includes(status.value)
                : true;
            const matchPublisher = publisher.value
                ? item.userName.includes(publisher.value)
                : true;
            const matchTitle = title.value
                ? item.title.includes(title.value)
                : true;

            return matchStatus && matchPublisher && matchTitle;
        });
    });

    //价格的格式化展示
    const formatPrice = (row: Form, column: Form, cellValue: number) => {
        return `${cellValue}元/小时`;
    };

    function getTableData() {
        axios
            .get(`/api/labor/works/${useridentityfer.value}`)
            .then((response) => {
                if (response.data.code == 200) {
                    tableData.value = response.data.data.map((item: Form) => ({
                        ...item,
                    }))
                }
                formatTableData(tableData.value);
            })
            .catch((error) => {
                alert(
                    "请求失败" + (error.response?.data?.message || "服务器错误")
                );
            });
    }

    function formatTableData(data: Form[]) {
        formatTable.value = data.map((item) => ({
            ...item,
            status: item.status === "1" ? "待审核" :
                item.status === "2" ? "审核通过" :
                    item.status === "3" ? "审核失败" : item.status,
            process: item.process === "1" ? "待接取" :
                item.process === "2" ? "已接取" :
                    item.process === "3" ? "经行中" :
                        item.process === "4" ? "已完成" :
                            item.process === "5" ? "已结算" : item.process,
            jobType: item.jobType === "1" ? "零工" :
                item.jobType === "3" ? "短期兼职" :
                    item.jobType === "2" ? "长期兼职" : item.jobType,
            publisher: item.userName,
        }))
        console.log("formatTable::", formatTable.value)
    }

    function addWork(currentRowData: Form) {
        return axios.post("/api/labor/addWork", currentRowData)
            .then(response => {
                return response; // 直接返回 axios 响应
            })
            .catch(error => {
                ElMessage.error("请求失败：" + (error.response?.data?.message || "服务异常"));
                throw error;
            });
    }

    // 侧边栏====================================================================
    function goJobTaker() {
        jobTakerStore.takersId = currentRowData.value.takersId;
        jobTakerStore.takersName = currentRowData.value.takersName;
        jobTakerStore.maxPeople = currentRowData.value.maxPeople;
        jobTakerStore.jobId = currentRowData.value.id;
        router.push({ name: "laberJobTaker" })
    }

    return {
        getTableData,
        steps,
        tableData,
        RowClick,
        currentRowData,
        drawer,
        handleSubmit,
        handleUpdate,
        openDrawer,
        handleDetail,
        handleDelete,
        multipleSelection,
        handleSelectChange,
        selectable,
        FlitTableData,
        flitItem,
        isEdit,
        formatPrice,
        optionItem,
        goJobTaker,
    };
}
